//
// Created by 崔世强 on 2018/3/30.
// Copyright (c) 2018 Facebook. All rights reserved.
//

import Foundation
import Kingfisher
import SnapKit
import UIKit

protocol GroupMemberInfoCellDelegate:class {
    func avatarBtnClick(cell:GroupMemberInfoCell)
}

enum CellType {
    case normal
    case plus
    case minus
}


class GroupMemberInfoCell: UICollectionViewCell {
    static let ID = "GroupMemberInfoCellID"
    
    var delegate:GroupMemberInfoCellDelegate?
    
    lazy var avatarBtn: UIButton = {
        let itemBtn = UIButton()
        itemBtn.layer.cornerRadius = 3
        itemBtn.layer.masksToBounds = true
        itemBtn.addTarget(self, action: #selector(btnClick), for: .touchUpInside)
        return itemBtn
    }()
    
    lazy var nameLabel: UILabel = {
        let itemL = UILabel()
        itemL.textColor = UIColor.gray
        itemL.font = UIFont.systemFont(ofSize: 11.0)
        itemL.textAlignment = .center
        return itemL
    }()
    
    var type:CellType = .normal {
        didSet {
            if type == .plus {
                self.avatarBtn.layer.borderWidth = 1
                self.avatarBtn.layer.borderColor = UIColor.lightGray.cgColor
                self.nameLabel.text = " "
                self.avatarBtn.setImage(#imageLiteral(resourceName: "plus"),for: .normal)
            } else if type == .minus {
                self.avatarBtn.layer.borderWidth = 1
                self.avatarBtn.layer.borderColor = UIColor.lightGray.cgColor
                self.nameLabel.text = " "
                self.avatarBtn.setImage(#imageLiteral(resourceName: "minus"),for: .normal)
            }
        }
    }
    
    var model:ChatGroupMember? {
        didSet {
            self.nameLabel.text = model?.contact?.remarkName ?? model?.nickName ?? model?.contact?.name ?? " "
            self.avatarBtn.layer.borderWidth = 0
            self.avatarBtn.kf.setImage(with: KF.ImageResource(downloadURL: Common.avatarUrl(model?.contact?.avatar ?? "") ?? URL(string: "localhost")!),
                                       for: .normal,placeholder: UIImage(named: "defaultAvatar"),options: [.processor(CryptorProcessor())])
        }
    }
    
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        self.addSubview(avatarBtn)
        self.addSubview(nameLabel)
        
        nameLabel.snp.makeConstraints { (make) in
            make.left.right.equalTo(self)
            make.bottom.equalTo(self.snp.bottom).offset(-5)
        }
        avatarBtn.snp.makeConstraints { (make) in
            make.width.height.equalTo(48)
            make.top.equalTo(self).offset(5)
            make.centerX.equalTo(self.snp.centerX)
        }
        
    }
    
    @objc func btnClick(_ btn:UIButton) {
        self.delegate?.avatarBtnClick(cell: self)
    }
    
}
